<template>
    <div>
        <div class="conta_main">
            <div v-if="searchForms.data.grades=='a17' || searchForms.data.grades == 'a14'">
                <div style="display: flex;align-items: baseline;"><h4>主三科-平均分排名</h4><span class="score_tag">取值：{{searchForms.data.scoreType==0? '原始分': '等级分'}}</span></div>
                <el-table
                    :data="props.dataList['mainList']" border highlight-current-row 
                    @sort-change="sortChange($event, props.dataList['mainList'])" :height="400" 
                    class="table student-down-table tabs" ref="table1" 
                    :header-cell-style="{background: '#f1f1f1', color: '#333',borderColor: 'rgb(193 193 193)'}">
                    <el-table-column label="班级名称" prop="className" align="center" min-width="90" header-align="center" :key="'aa'" fixed show-overflow-tooltip>
                        <template #default="scope">
                            <el-button type="primary" link @click="toClassKanban(scope.row)" class="idAddName">{{scope.row.className}}</el-button>   
                        </template>
                    </el-table-column>
                    <template v-for="(item,index) in subjectList.data" :key="index">
                        <el-table-column :label="item.name" width="100" :prop="item.props" align="right" header-align="center" :sort-orders="['ascending', 'descending']" sortable="column"></el-table-column>
                        <el-table-column label="校区排名" width="110" :prop="item.props + 'AreaRank'" align="right" header-align="center" :sort-orders="['ascending', 'descending']" sortable="column"></el-table-column>
                        <el-table-column v-if="index==0" label="年级排名" width="110" :prop="item.props + 'GradeRank'" align="right" header-align="center">
                            <template #header="scope">                                                                
                                <div @click="defaultSort = (defaultSort=='null' ? true : !defaultSort)" class="pointer-btn">
                                    <!-- <prompt-message tipType="middle" :scope="scope" :dataList="dataList" :middle="c.abProp+'Middle'" :many="c.abProp+'Many'"> -->
                                        <!-- <span slot="columnName"> -->
                                            <span>{{scope.column.label}}</span>
                                            <span class="caret-wrapper">
                                                <!-- 升序 -->
                                                <i class="sort-caret ascending" :class="{'default-sort': (defaultSort && defaultSort !='null')}"></i>
                                                <!-- 降序 -->
                                                <i class="sort-caret descending" :class="{'default-sort': !defaultSort && defaultSort != 'null'}"></i>
                                            </span>
                                        <!-- </span>  -->
                                    <!-- </prompt-message> -->
                                </div>                               
                            </template> 
                        </el-table-column>
                        <el-table-column v-else label="年级排名" width="110" :prop="item.props + 'GradeRank'" align="right" header-align="center" :sort-orders="['ascending', 'descending']" sortable="column"></el-table-column>
                    </template>                
                </el-table>

                <template v-for="(tableItem, tableIndex) in tableList.data" :key="tableIndex">
                    <div style="display: flex;align-items: baseline;"><h4>{{tableItem.name}}</h4><span class="score_tag">取值：{{searchForms.data.scoreType==0? '原始分': '等级分'}}</span></div>
                    <el-table
                        :data="props.dataList[tableItem.list]" border highlight-current-row 
                        @sort-change="sortChange($event, props.dataList[tableItem.list],'more', tableIndex)" :height="400" style="width: 50%"
                        class="table student-down-table tabs" :ref="`multipleTable${tableIndex+1}`" :class="`multipleTable${tableIndex+1}`"
                        :header-cell-style="{background: '#f1f1f1', color: '#333',borderColor: 'rgb(193 193 193)'}">
                        <el-table-column label="班级名称" prop="className" align="center" min-width="90" header-align="center">
                            <template #default="scope">
                                <el-button type="primary" link @click="toClassKanban(scope.row)" class="idAddName">{{scope.row.className}}</el-button>   
                            </template>
                        </el-table-column>
                        <el-table-column label="授课教师" prop="teacherName" align="center" header-align="center"></el-table-column>
                        <el-table-column :label="tableItem.column" prop="score" align="right" header-align="center" :sort-orders="['ascending', 'descending']" sortable="column"></el-table-column>
                        <el-table-column label="校区排名" prop="areaRank" align="right" header-align="center" :sort-orders="['ascending', 'descending']" sortable="column"></el-table-column>
                        <el-table-column label="年级排名" prop="gradeRank" align="right" header-align="center">
                            <template #header="scope">                                                                
                                <div @click="tableItem.defaultSort = (tableItem.defaultSort=='null' ? true : !tableItem.defaultSort)" class="pointer-btn">
                                    <!-- <prompt-message tipType="middle" :scope="scope" :dataList="dataList" :middle="c.abProp+'Middle'" :many="c.abProp+'Many'"> -->
                                        <!-- <span slot="columnName"> -->
                                            <span>{{scope.column.label}}</span>
                                            <span class="caret-wrapper">
                                                <!-- 升序 -->
                                                <i class="sort-caret ascending" :class="{'default-sort': (tableItem.defaultSort && tableItem.defaultSort !='null')}"></i>
                                                <!-- 降序 -->
                                                <i class="sort-caret descending" :class="{'default-sort': !tableItem.defaultSort && tableItem.defaultSort != 'null'}"></i>
                                            </span>
                                        <!-- </span>  -->
                                    <!-- </prompt-message> -->
                                </div>                               
                            </template> 
                        </el-table-column>
                    </el-table>
                </template>
            </div>
            <div v-else>
                <div style="margin: 20px 0 0 0px;">
                    <span class="score_tag">颜色说明：红色表示 比总分排名低；绿色表示 比总分排名高；橙色表示 与总分排名一致。</span>
                </div>
                    <!-- :cell-style="cellStyle" -->
                <el-table
                    :data="props.dataList['avgList'] && props.dataList['avgList']['classList']" border highlight-current-row :cell-class-name="addClass" 
                    class="table" ref="avgTable" @sort-change="sortChange($event, props.dataList['avgList'] && props.dataList['avgList']['classList'])" show-summary :summary-method="getSummaries"
                    :header-cell-style="{background: '#f1f1f1', color: '#333'}" style="width: 100%"
                >
                    <el-table-column prop="className" label="班级" header-align="center" align="center" fixed :key="'bb'">
                        <template #default="scope">
                            <el-button type="primary" link @click="toClassKanban(scope.row)" class="idAddName">{{scope.row.className}}</el-button>   
                        </template>
                    </el-table-column>
                    <el-table-column label="班主任" prop="masterName" header-align="center" align="center" min-width="200"></el-table-column>
                    <template v-for="(c,i) in columnsList" :key="i">
                        <template v-if="i!=0">
                            <el-table-column :prop="c.props+'Teacher'" label="授课教师" :sort-orders="['ascending', 'descending']" sortable="column" min-width="120" :key="i+'aa'" header-align="center" align="center">
                                <template #default="scope">
                                    <span>{{scope.row[c.props+'Teacher'] ? scope.row[c.props+'Teacher'] : '-'}}</span>
                                </template>
                            </el-table-column>
                        </template>
                        <el-table-column :prop="c.props+'Score'" :label="c.name" :sort-orders="['ascending', 'descending']" sortable="column" header-align="center" :align="c.align" :width="c.width? c.width: ''"></el-table-column>

                        <el-table-column v-if="i==0" :prop="c.props+'Rank'" label="排名" class="hover_column" header-align="center" :align="c.align">
                            <template #header="scope">                                                                
                                <div @click="defaultSort = (defaultSort=='null' ? true : !defaultSort)" class="pointer-btn">
                                    <!-- <prompt-message tipType="middle" :scope="scope" :dataList="dataList" :middle="c.abProp+'Middle'" :many="c.abProp+'Many'"> -->
                                        <!-- <span slot="columnName"> -->
                                            <span>{{scope.column.label}}</span>
                                            <span class="caret-wrapper">
                                                <!-- 升序 -->
                                                <i class="sort-caret ascending" :class="{'default-sort': (defaultSort && defaultSort !='null')}"></i>
                                                <!-- 降序 -->
                                                <i class="sort-caret descending" :class="{'default-sort': !defaultSort && defaultSort != 'null'}"></i>
                                            </span>
                                        <!-- </span>  -->
                                    <!-- </prompt-message> -->
                                </div>                               
                            </template> 
                        </el-table-column>
                        <el-table-column v-else :prop="c.props+'Rank'" label="排名" :sort-orders="['ascending', 'descending']" sortable="column"  class="hover_column" header-align="center" :align="c.align"></el-table-column>
                    </template>
                </el-table>
            </div>
        </div>
    </div>
</template>
<script setup>//查询维度-平均分
import {sort} from '@/utils/helper';
import { getCurrentInstance, nextTick, onMounted, reactive, ref, watch } from 'vue';
let props = defineProps({
    dataList: Object,
    searchForm: Object,
    searchForms1: Object,
});
let defaultSort=ref();//默认表格排序
const instance = getCurrentInstance();
let avgList=reactive([]);
let tableList=reactive({data: []});
let searchForms=reactive({
    data: {}
});
let subjectList=reactive({
    data: [
        {id: 100,name: '总分',props: 'all'},{id: 212,name: '语数英',props: 'cme'},{id: 101,name: '语文',props: 'ch'},
        {id: 102,name: '数学',props: 'ma'},{id: 103,name: '英语',props: 'en'},{id: 104,name: '听说',props: 'hear'},                
    ]
});
let columnsList= reactive([
    {name: '总分',props: 'all',align: 'center',},
    {name: '语数英',props: 'cme',align: 'right',width: 90},
    {name: '语文',props: 'cn',align: 'right',},
    {name: '数学',props: 'ma',align: 'right',},
    {name: '英语',props: 'en',align: 'right',},
    {name: '物理',props: 'ph',align: 'right',},
    {name: '化学',props: 'ch',align: 'right',},
    {name: '生物',props: 'bi',align: 'right',},
    {name: '历史',props: 'hi',align: 'right',},
    {name: '地理',props: 'ge',align: 'right',},
    {name: '政治',props: 'po',align: 'right',},
]);
let isDel=ref(false);
let sumlist=reactive({});
let subColumn=reactive(['all','cme','cn','ma','en','ph','ch','bi','hi','ge','po']);
const emit = defineEmits(['classTo1']);
onMounted(()=>{
    searchForms.data = props.searchForm;
    avgList = props.dataList['avgList'];
    getColumnList();
});
let initPage=()=>{
    // setTimeout(()=>{
        nextTick(() => {//解决固定列错位问题
            getColumnList();  
            // _this.handlerDefaultSort(); //默认排序总分排名 升序 
        });
        // }
        
    // }, 100)  
};
/**
 * 清除类
 */
let clearClassName=(tableIndex)=>{
    let currentTable = document.querySelector(`.multipleTable${tableIndex+1}`);
    var selfClassName = [];
    if(currentTable){//因为表格是循环的，所以在排序的时候，不影响 其他表格
        selfClassName = currentTable.getElementsByClassName("is-sortable");
    }else{
        selfClassName = document.getElementsByClassName("is-sortable");
    }
    var hasDescendingClassNameStt = false;
    var hasAscendingClassNameStt = false;
    for(var a =0;a<selfClassName.length;a++){
        // 清除倒序className
        hasDescendingClassNameStt = selfClassName[a].classList.contains('descending');
        if(hasDescendingClassNameStt){
            selfClassName[a].classList.remove('descending')
        }
        // 清除正序className
        hasAscendingClassNameStt = selfClassName[a].classList.contains('ascending');
        if(hasAscendingClassNameStt){
            selfClassName[a].classList.remove('ascending')
        }
    }
};
//还原默认排序
let restoreDefaultSort=()=>{
    defaultSort.value = true;
    clearClassName();
};
// 科目的循环设置默认排序
let moreDefaultSort=(defaultSort, name, tableIndex)=>{ 
    if(instance.refs[`multipleTable${tableIndex+1}`]){
        clearClassName(tableIndex);
        instance.refs[`multipleTable${tableIndex+1}`][0].clearSort();
    }     
    let order = '';
    if(defaultSort){//为true则为升序
        order='ascending';
    }else{
        order ='descending';
    }
    if(props.dataList[name] && props.dataList[name].length){
        if(props.dataList[name][0].hasOwnProperty('gradeRank')){//总分排名 排序
            sort(props.dataList[name], 'gradeRank', order=='ascending');
        }
    }
};
    /**
 * 页面渲染默认排序
 */
let handlerDefaultSort=()=>{
    if(searchForms.data.grades=='a11'){
        if(instance.refs.avgTable){
            clearClassName();
            instance.refs.avgTable.clearSort();
        }     
    }else{                
        if(instance.refs.table1){
            clearClassName();
            instance.refs.table1.clearSort();
        }     
    }
        
    let order = '';
    if(defaultSort.value){//为true则为升序
        order='ascending';
    }else{
        order ='descending';
    }
    if(searchForms.data.grades=='a11'){
        if(props.dataList && props.dataList.avgList && props.dataList.avgList['classList'].length){
            if(props.dataList.avgList['classList'][0].hasOwnProperty('allRank')){//总分排名 排序
                sort(props.dataList.avgList['classList'], 'allRank', order=='ascending');
            }
        }
    }else{
        if(props.dataList && props.dataList.mainList && props.dataList.mainList.length){
            if(props.dataList.mainList[0].hasOwnProperty('allGradeRank')){//总分排名 排序
                sort(props.dataList.mainList, 'allGradeRank', order=='ascending');
            }
        }
    }
};    
/**
 * 表头排序
 */
let sortChange=(val, dataList, type, tableIndex)=>{ 
    if(type){
        if(val.prop != 'allGradeRank' && val.prop !='gradeRank'){
            tableList.data[tableIndex]['defaultSort'] = 'null';
        }else{
            clearClassName();
        }
    }else{
        if(val.prop != 'allRank'){
            defaultSort.value = 'null';
        }else{
            clearClassName();
        } 
    }
    sort(dataList, val.prop, val.order=='ascending');
};
let cellStyle=({row, column, rowIndex, columnIndex})=>{
    if(rowIndex ===  props.dataList['avgList']['classList'].length-1){ //指定坐标rowIndex ：行，columnIndex ：列
        return 'background:#F5F7FA' //rgb(105,0,7)
    }else{
        return ''
    }
};
//求和
let getSummaries=(param)=>{   
    nextTick(() => {//第一次加载合计行不显示问题，重新渲染一次
        if(instance.refs.avgTable){
            instance.refs.avgTable.doLayout();
        }
    });
    const { columns, data } = param;
    const sums = [];
    let gradeList = props.dataList['avgList'] && props.dataList['avgList']['gradeList']&&props.dataList['avgList']['gradeList'][0];
    if(!gradeList){ return false; }
    columns.forEach((column, index) => {
        sums.push(gradeList[column['property']]);         
    });               
    return sums;
};
//设置单元格背景色
let addClass=({row,column,rowIndex,columnIndex})=>{
    /*if(columnIndex==6){
        return _this.getColor(row, 'cme');
    }*/
    if(columnIndex >3 && columnIndex%3===0){
        for(let i = 0; i< subColumn.length; i++){
            let index = i;
            let item = subColumn[i];
            
            if(index!=0 && (columnIndex/3)== (index+1)){
                return getColor(row, item);
            }
        }
    }
};
//指定单元格 设置class
let getColor=(row, item)=>{
    let rowBackground = '';
    if(row.allRank==''&& row.allRank!==0){
        return '';
    }
    if(row[item+'Rank'] > row.allRank){
        rowBackground='cell_xiaoyu';
    }else if(row[item+'Rank'] == row.allRank){
        rowBackground='cell_dengyu';
    }else if(row[item+'Rank'] < row.allRank){
        rowBackground='cell_dayu';
    }
    return rowBackground;
};
//
let getColumnList=()=>{
    // if(this.searchForms.grades!='a11'){
    //     this.defaultSort = "null";
    //     this.clearClassName();
    // }else{
    defaultSort.value = true;
    clearClassName();
    handlerDefaultSort(); //默认排序A-B
    // }
    tableList.data = [];
    tableList.data = [
        {name:'物理-平均分排名',list: 'phyRank',column: '物理',type: '原始分',defaultSort: true},
        {name:'化学-平均分排名',list: 'cmeRank',column: '化学',type: '原始分',defaultSort: true},
        {name:'生物-平均分排名',list: 'bioRank',column: '生物',type: '原始分',defaultSort: true},
        {name:'历史-平均分排名',list: 'hisRank',column: '历史',type: '原始分',defaultSort: true},
        {name:'地理-平均分排名',list: 'geoRank',column: '地理',type: '原始分',defaultSort: true},
        {name:'政治-平均分排名',list: 'polRank',column: '政治',type: '原始分',defaultSort: true}
    ];
    /*   let datas = JSON.parse(JSON.stringify(_this.dataList['avgList']));
    datas.splice(datas.length-1);
    _this.avgList = datas;
    _this.sumlist = _this.dataList['avgList'][_this.dataList['avgList'].length-1]; */
    nextTick(()=>{
        if(instance.refs.avgTable){
            instance.refs.avgTable.doLayout();
        }
    })
};
//班级看板（行政班）
let toClassKanban=(row)=>{
    let params = {
        className:row.className,
        classId:row.classId,//班级ID
        isScoreType: props.dataList['grade'] == 17, //分数类型 0原始分 1等级分   高三才有等级分，其他默认原始分
        scoreType: searchForms.data.scoreType,//0原始分 1等级分
        yearly: props.searchForm.yearly,
        testId: props.dataList['testIdA'],
        testIdA: props.dataList['testIdA'],//考试批次ID
        testIdB: props.dataList['testIdB'],
        subjectId: row.subjectId,
        subjectName: row.subjectName,
        grade: props.searchForm.grade,//年级
        classType: row.classType,//classType: 0行政班；1教学班；
    }
    emit('classTo1', params);
};
watch(()=>props.searchForms1,(val)=>{
    initPage();
}, {deep: true});
watch(()=>props.dataList,(val)=>{
    // initPage();
}, {deep: true});
watch(()=>defaultSort,(newVal, oldVal)=>{
    if(newVal == 'null'){//排序不是默认的，要把默认排序清空
        return false;
    }
    handlerDefaultSort();
}, {deep: true});
watch(()=>tableList.data[0] && tableList.data[0]['defaultSort'],(val)=>{
    if(val == 'null'){//排序不是默认的，要把默认排序清空
        return false;
    }
    moreDefaultSort(val,'phyRank',0);
}, {deep: true});
watch(()=>tableList.data[1] && tableList.data[1]['defaultSort'],(val)=>{
    if(val == 'null'){//排序不是默认的，要把默认排序清空
        return false;
    }
    moreDefaultSort(val,'cmeRank',1);
}, {deep: true});
watch(()=>tableList.data[2] && tableList.data[2]['defaultSort'],(val)=>{
    if(val == 'null'){//排序不是默认的，要把默认排序清空
        return false;
    }
    moreDefaultSort(val,'bioRank',2);
}, {deep: true});
watch(()=>tableList.data[3] && tableList.data[3]['defaultSort'],(val)=>{
    if(val == 'null'){//排序不是默认的，要把默认排序清空
        return false;
    }
    moreDefaultSort(val,'hisRank',3);
}, {deep: true});
watch(()=>tableList.data[4]&&tableList.data[4]['defaultSort'],(val)=>{
    if(val == 'null'){//排序不是默认的，要把默认排序清空
        return false;
    }
    moreDefaultSort(val,'geoRank',4);
}, {deep: true});
watch(()=>tableList.data[5] && tableList.data[5]['defaultSort'],(val)=>{
    if(val == 'null'){//排序不是默认的，要把默认排序清空
        return false;
    }
    moreDefaultSort(val,'polRank',5);
}, {deep: true});

</script>
<style lang="scss" scoped>
.conta_main{
    h4{
        margin-top: 20px;
    }
    .score_tag{
        font-size: 14px;
        color: #02a7f0;
        margin-left: 20px;
    }
    /* 负数 */
    .minus-number{
        color: red;
    }
    .positive-number{
        color: #70B603;
    }
}
</style>